package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    //定义超时时间
    public static long tokenExpiration = 1000 * 60 * 60;
    //定义秘钥
    public static SecretKey tokenSecretKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWQvP70B90lTpGYX1d4AQ".getBytes());

    //定义生成token的方法
    public static String createJwtToken(Long userId) {
        String token = Jwts.builder()
                .setSubject("USER_INFO")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .signWith(tokenSecretKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //定义解析token的方法
    public static Long getJwtToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    //密钥
                    .setSigningKey(tokenSecretKey)
                    //进行解密
                    .build()
                    .parseClaimsJws(token);
            Long userId = claimsJws.getBody().get("userId",Long.class);
            return userId;
        } catch (Exception e) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

    }
}
